package zozopo.user.filter;

import java.io.IOException;   
import javax.servlet.Filter;   
import javax.servlet.FilterChain;   
import javax.servlet.FilterConfig;   
import javax.servlet.ServletException;   
import javax.servlet.ServletRequest;   
import javax.servlet.ServletResponse;   
import javax.servlet.http.Cookie;   
import javax.servlet.http.HttpServletRequest;   
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpSession;

import zozopo.user.operations.TokenOS;
import zozopo.user.operations.TokenTB;
import zozopo.user.operations.UserOS;
import zozopo.user.operations.UserTB;

public class FilterUser  implements Filter {   
    public void destroy() {   
        // TODO Auto-generated method stub   
    }   
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,   
            FilterChain filterChain) throws IOException, ServletException { 
    
        HttpServletRequest request = (HttpServletRequest) servletRequest;   
        HttpServletResponse response = (HttpServletResponse) servletResponse;   
        HttpSession session = request.getSession();
        
        if(session.isNew()){
        	UserTB userInfo = (UserTB)request.getSession().getAttribute("userInfo");
            
            
         	   
         	   TokenOS tokenOS = new TokenOS();
                UserOS userOS = new UserOS(tokenOS.getConn());
                Cookie[] cookies = request.getCookies();  

                if (cookies != null) {
                	TokenTB token = tokenOS.getToken(cookies);
     	           	if(token!=null){
     	           		userInfo = userOS.getUserInfoByName(token.getUsername());
     	               	request.getSession().setAttribute("userInfo", userInfo);
     	           	}
                }
        
                tokenOS.releaseConnection();
           
          
       }//
        
      
     
        filterChain.doFilter(servletRequest, servletResponse); 
    }   
    public void init(FilterConfig arg0) throws ServletException {   
        // TODO Auto-generated method stub   
    }   


}
